Page({
  data: {
    categoryList: [],
    dishList: [],
    cartList: [],
    activeCategory: 0,
    scrollTop: 0
  },
  onLoad: function() {
    console.log('商品页面加载');
    this.getCategoryList();
    this.getCartList();
  },
  // 获取分类列表
  getCategoryList: function() {
    const that = this;
    // 从全局获取token
    const app = getApp();
    const token = app.globalData.token;
    
    wx.request({
      url: 'http://localhost:8080/user/category/list',
      method: 'GET',
      header: token ? { 'Authorization': token } : {},
      success: function(res) {
        if (res.data && res.data.code === 1) {
          that.setData({
            categoryList: res.data.data || []
          });
          // 如果有分类，获取第一个分类的菜品
          if (res.data.data && res.data.data.length > 0) {
            that.getDishList(res.data.data[0].id);
          }
        }
      },
      fail: function(err) {
        console.error('获取分类失败', err);
      }
    });
  },
  // 获取菜品列表
  getDishList: function(categoryId) {
    const that = this;
    // 从全局获取token
    const app = getApp();
    const token = app.globalData.token;
    
    wx.request({
      url: 'http://localhost:8080/user/dish/list',
      method: 'GET',
      data: {
        categoryId: categoryId
      },
      header: token ? { 'Authorization': token } : {},
      success: function(res) {
        if (res.data && res.data.code === 1) {
          that.setData({
            dishList: res.data.data || []
          });
        }
      },
      fail: function(err) {
        console.error('获取菜品失败', err);
      }
    });
  },
  // 获取购物车列表
  getCartList: function() {
    const that = this;
    // 从全局获取token
    const app = getApp();
    const token = app.globalData.token;
    
    wx.request({
      url: 'http://localhost:8080/user/shoppingCart/list',
      method: 'GET',
      header: token ? { 'Authorization': token } : {},
      success: function(res) {
        if (res.data && res.data.code === 1) {
          that.setData({
            cartList: res.data.data || []
          });
        }
      },
      fail: function(err) {
        console.error('获取购物车失败', err);
      }
    });
  },
  // 切换分类
  switchCategory: function(e) {
    const index = e.currentTarget.dataset.index;
    const categoryId = this.data.categoryList[index].id;
    
    this.setData({
      activeCategory: index,
      scrollTop: 0
    });
    
    this.getDishList(categoryId);
  },
  // 添加到购物车
  addToCart: function(e) {
    const dish = e.currentTarget.dataset.dish;
    // 购物车操作逻辑
  },
  // 从购物车移除
  removeFromCart: function(e) {
    const dish = e.currentTarget.dataset.dish;
    // 购物车操作逻辑
  }
})
